<template>
  <div class="login">
    <el-form
      ref="loginRef"
      :validate-on-rule-change="false"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      v-show="!showResetAccount"
    >
      <div class="title">约饭派后台管理系统</div>
      <el-menu
        :class="{ 'justify-space-evenly': defaultIndex === '0' }"
        :default-active="defaultIndex"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-menu-item v-if="firstLogin === '0'" index="0"> 账号密码登录 </el-menu-item>
        <el-menu-item index="1"> 手机号登录 </el-menu-item>
      </el-menu>
      <el-form-item></el-form-item>
      <template v-if="loginType === '0'">
        <el-form-item prop="username">
          <el-input
            v-model.trim="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            maxlength="11"
            placeholder="账号"
          >
            <template #prefix>
              <svg-icon icon-class="user" class="el-input__icon input-icon" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model.trim="loginForm.password"
            type="password"
            size="large"
            maxlength="16"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <svg-icon icon-class="password" class="el-input__icon input-icon" />
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            type="text"
            maxlength="11"
            size="large"
            placeholder="手机号"
          >
            <template #prefix>
              <svg-icon icon-class="phone" class="el-input__icon input-icon" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="smsCode">
          <div class="justify-space-between">
            <el-input
              maxlength="6"
              v-model.trim="loginForm.smsCode"
              size="large"
              placeholder="验证码"
              @keyup.enter="handleLogin"
              clearable
            >
              <template #prefix>
                <svg-icon icon-class="email" class="el-input__icon input-icon" />
              </template>
            </el-input>
            <el-button plain class="sms-button" @click="getSmsCode" :disabled="disabled">
              {{ btnText }}
            </el-button>
          </div>
        </el-form-item>
      </template>
      <el-form-item>
        <div class="justify-space-between">
          <el-checkbox v-model="loginForm.checked">
            <el-link type="primary" @click="handleAction('agreeMent')"> 用户协议</el-link>
          </el-checkbox>
          <el-button @click="handleAction('resetAccount')" text type="primary">忘记密码</el-button>
        </div>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width: 100%"
          @click.prevent="handleLogin"
        >
          {{ loading ? '登 录 中...' : '登 录' }}
        </el-button>
      </el-form-item>
    </el-form>

    <reset-account @turnBack="handleAction('resetAccount')" v-show="showResetAccount" />

    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2025 杭州约饭派科技有限公司</span>
    </div>
  </div>
  <canvas id="canvas" class="canvas"></canvas>
</template>

<script setup>
import { encrypt } from '@/utils/jsencrypt'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { useParticleEffects } from '@/hooks/useParticleEffects'
import { useCountButton } from '@/hooks/common'
import { formRules } from '@/utils/valid/formRules'
import { sendSmsCode } from '@/api/login'

const route = useRoute()
const router = useRouter()
const firstLogin = useLocalStorage('yfp-firstLogin', '1')
const { disabled, btnText, startCount } = useCountButton()

const defaultIndex = ref(unref(firstLogin))
const loginType = ref(unref(firstLogin))
const userStore = useUserStore()
const loginRef = ref(null)
const showResetAccount = ref(false)

// 粒子特效
onMounted(useParticleEffects)

const loginForm = reactive({
  username: '',
  password: '',
  phone: '',
  smsCode: '',
  checked: null
})
const loginRules = ref({})
const loading = ref(false)

onMounted(() => {
  if (route.query.root) {
    firstLogin.value = '0'
  }
  console.log(firstLogin.value)
  console.log(loginType.value)
})

watchEffect(() => {
  loginRules.value =
    loginType.value === '0'
      ? {
          username: formRules.set('请输入您的账号'),
          password: formRules.set('请输入您的密码')
        }
      : {
          phone: formRules.phone,
          smsCode: formRules.set('请输入收到的验证码')
        }
})

const handleSelect = (key) => {
  loginType.value = key
  loginRef.value?.resetFields()
}

function handleLogin() {
  loginRef.value.validate((valid) => {
    if (valid) {
      if (!loginForm.checked) {
        ElMessage.info('请先阅读并勾选用户协议!')
        return
      }
      loading.value = true
      // 调用action的登录方法
      const parmas = { ...loginForm }
      // 密码加密
      if (parmas.password) parmas.password = encrypt(parmas.password)
      userStore
        .login(parmas)
        .then(() => {
          firstLogin.value = '0'

          router.push({ path: '/' })
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

function handleAction(type) {
  if (type === 'agreeMent') {
    window.open('./html/protocol.pdf')
  } else {
    loginRef.value?.resetFields()
    showResetAccount.value = !showResetAccount.value
  }
}

function getSmsCode() {
  loginRef.value.validateField('phone', (valid) => {
    if (valid) {
      sendSmsCode(loginForm.phone).then(startCount)
    }
  })
}
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.el-menu {
  border-bottom: none;
  .el-menu-item {
    font-size: 16px;
  }
}
.title {
  font-size: 30px;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  min-width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
  .sms-button {
    width: 7em;
    height: 40px;
    margin-left: 1em;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 20px;
  width: 100%;
  text-align: center;
  color: #333;
  font-family: Arial;
  font-size: 14px;
  letter-spacing: 1px;
}

.canvas {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  width: 100vw;
  height: 100vh;
  background: transparent;
}
.justify-space-between {
  width: 100%;
}
</style>
